<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" :width="800" @ok="handleSubmit" @cancel="handleCancel">
    <div class="p-4">
      <a-form ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="订单号" name="orderCode">
          <a-input :value="formData.orderCode" disabled />
        </a-form-item>
        <a-form-item label="选择护工" name="nurseId" :rules="[{ required: true, message: '请选择护工' }]">
          <a-select
            v-model:value="formData.nurseId"
            placeholder="请选择护工"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            @change="handleNurseChange"
          >
            <a-select-option v-for="nurse in nurseList" :key="nurse.id" :value="nurse.id" :label="nurse.name">
              {{ nurse.name }} - {{ nurse.phone }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="护工姓名" name="nurseName">
          <a-input :value="formData.nurseName" disabled />
        </a-form-item>
      </a-form>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { list as getNurseList } from '/@/views/nurse/nurse_nurses/NurseNurses.api';
  import { saveOrUpdate } from '../MedicationOrder.api';

  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);

  const title = ref('订单分配');
  const formRef = ref();
  const nurseList = ref<any[]>([]);

  const formData = reactive({
    id: '',
    orderCode: '',
    nurseId: '',
    nurseName: '',
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });

    // 重置表单
    Object.assign(formData, {
      id: data.record?.id || '',
      orderCode: data.record?.code || '',
      nurseId: data.record?.nurseId || '',
      nurseName: data.record?.nurseName || '',
    });

    // 加载护工列表
    await loadNurseList();

    await nextTick();
    formRef.value?.clearValidate();
  });

  /**
   * 加载护工列表
   */
  async function loadNurseList() {
    try {
      const response = await getNurseList({});
      if (response && response.records) {
        nurseList.value = response.records;
      } else if (Array.isArray(response)) {
        nurseList.value = response;
      } else {
        nurseList.value = [];
      }
    } catch (error) {
      console.error('加载护工列表失败:', error);
      createMessage.error('加载护工列表失败');
      nurseList.value = [];
    }
  }

  /**
   * 护工选择变化处理
   */
  function handleNurseChange(nurseId: string) {
    const selectedNurse = nurseList.value.find((nurse) => nurse.id === nurseId);
    if (selectedNurse) {
      formData.nurseName = selectedNurse.name;
    } else {
      formData.nurseName = '';
    }
  }

  /**
   * 选项过滤
   */
  function filterOption(input: string, option: any) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  /**
   * 提交处理
   */
  async function handleSubmit() {
    try {
      await formRef.value?.validate();

      setModalProps({ confirmLoading: true });

      const updateData = {
        id: formData.id,
        nurseId: formData.nurseId,
        nurseName: formData.nurseName,
        status: '10', // 分配订单后将状态改为10
      };

      await saveOrUpdate(updateData, true);

      createMessage.success('订单分配成功');
      closeModal();
      emit('success');
    } catch (error) {
      console.error('订单分配失败:', error);
      createMessage.error('订单分配失败，请稍后重试');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  /**
   * 取消处理
   */
  function handleCancel() {
    closeModal();
  }
</script>